<template>
  <div class="chat-container">
    <!-- 消息区域 -->
    <div class="messages" ref="messagesRef">
      <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="['message-row', msg.role]"
      >
        <div v-if="msg.role === 'user'" class="bubble user-bubble">
          {{ msg.content }}
        </div>
        <div v-else class="bubble assistant-bubble">
          {{ msg.content }}
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <el-input
          v-model="inputMessage"
          placeholder="请输入你的问题..."
          type="textarea"
          :rows="2"
          resize="none"
      />
      <el-button type="primary" @click="sendMessage">发送</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick } from "vue";
import { chatApi } from "@/api/core";

interface Message {
  role: "user" | "assistant";
  content: string;
}

const messages = ref<Message[]>([
  { role: "assistant", content: "你好，我是智能助手，有什么可以帮你？" },
]);
const inputMessage = ref("");
const messagesRef = ref<HTMLDivElement | null>(null);

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return;
  messages.value.push({ role: "user", content: inputMessage.value });
  await nextTick();
  scrollToBottom();
  try {
    const res = await chatApi.sendMessage(inputMessage.value);
    const reply = res.data?.message || res.data || "服务端没有返回数据";
    messages.value.push({ role: "assistant", content: reply });
  } catch (err) {
    messages.value.push({ role: "assistant", content: "请求失败，请检查服务端" });
  }
  inputMessage.value = "";
  await nextTick();
  scrollToBottom();
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight;
  }
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #f5f7fa;
  padding: 16px;
  box-sizing: border-box;
}

/* 消息区域，自动滚动 */
.messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 每条消息 */
.message-row {
  display: flex;
  align-items: flex-start;
}

.message-row.user {
  justify-content: flex-end;
}

.message-row.assistant {
  justify-content: flex-start;
}

/* 气泡 */
.bubble {
  max-width: 70%;
  padding: 10px 14px;
  border-radius: 18px;
  line-height: 1.4;
  font-size: 14px;
  word-break: break-word;
}

.user-bubble {
  background: var(--el-color-primary);
  color: #fff;
  border-bottom-right-radius: 4px;
}

.assistant-bubble {
  background: #fff;
  border: 1px solid #ebeef5;
  border-bottom-left-radius: 4px;
  color: #303133;
  box-shadow: 0 2px 6px rgba(0,0,0,0.05);
}

/* 输入区域固定在底部 */
.input-area {
  display: flex;
  gap: 10px;
  align-items: flex-end;
  padding-top: 8px;
  border-top: 1px solid #ebeef5;
  background: #fff;
}
</style>
